package models

import (
	"database/sql"
	"fmt"
	"time"
)

type Order struct {
	ID        int64     `json:"id"`
	UserID    int64     `json:"user_id"`
	Product   string    `json:"product"`
	Amount    float64   `json:"amount"`
	Status    string    `json:"status"`
	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`
}

type OrderRepository struct {
	db *sql.DB
}

func NewOrderRepository(db *sql.DB) *OrderRepository {
	return &OrderRepository{db: db}
}

// CreateTable 创建订单表
func (r *OrderRepository) CreateTable() error {
	query := `
	CREATE TABLE IF NOT EXISTS orders (
		id BIGINT AUTO_INCREMENT PRIMARY KEY,
		user_id BIGINT NOT NULL,
		product VARCHAR(255) NOT NULL,
		amount DECIMAL(10,2) NOT NULL,
		status VARCHAR(50) DEFAULT 'pending',
		created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
		updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
		INDEX idx_user_id (user_id),
		INDEX idx_status (status)
	) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;`

	_, err := r.db.Exec(query)
	if err != nil {
		return fmt.Errorf("failed to create orders table: %w", err)
	}
	return nil
}

// Create 创建订单
func (r *OrderRepository) Create(order *Order) error {
	query := `INSERT INTO orders (user_id, product, amount, status) VALUES (?, ?, ?, ?)`
	result, err := r.db.Exec(query, order.UserID, order.Product, order.Amount, order.Status)
	if err != nil {
		return fmt.Errorf("failed to create order: %w", err)
	}

	id, err := result.LastInsertId()
	if err != nil {
		return fmt.Errorf("failed to get last insert id: %w", err)
	}

	order.ID = id
	return nil
}

// GetByID 根据ID获取订单
func (r *OrderRepository) GetByID(id int64) (*Order, error) {
	query := `SELECT id, user_id, product, amount, status, created_at, updated_at FROM orders WHERE id = ?`
	
	order := &Order{}
	err := r.db.QueryRow(query, id).Scan(
		&order.ID,
		&order.UserID,
		&order.Product,
		&order.Amount,
		&order.Status,
		&order.CreatedAt,
		&order.UpdatedAt,
	)
	
	if err != nil {
		if err == sql.ErrNoRows {
			return nil, fmt.Errorf("order not found")
		}
		return nil, fmt.Errorf("failed to get order: %w", err)
	}

	return order, nil
}

// GetByUserID 根据用户ID获取订单列表
func (r *OrderRepository) GetByUserID(userID int64) ([]*Order, error) {
	query := `SELECT id, user_id, product, amount, status, created_at, updated_at FROM orders WHERE user_id = ? ORDER BY created_at DESC`
	
	rows, err := r.db.Query(query, userID)
	if err != nil {
		return nil, fmt.Errorf("failed to get orders: %w", err)
	}
	defer rows.Close()

	var orders []*Order
	for rows.Next() {
		order := &Order{}
		err := rows.Scan(
			&order.ID,
			&order.UserID,
			&order.Product,
			&order.Amount,
			&order.Status,
			&order.CreatedAt,
			&order.UpdatedAt,
		)
		if err != nil {
			return nil, fmt.Errorf("failed to scan order: %w", err)
		}
		orders = append(orders, order)
	}

	return orders, nil
}

// UpdateStatus 更新订单状态
func (r *OrderRepository) UpdateStatus(id int64, status string) error {
	query := `UPDATE orders SET status = ? WHERE id = ?`
	_, err := r.db.Exec(query, status, id)
	if err != nil {
		return fmt.Errorf("failed to update order status: %w", err)
	}
	return nil
}

// Delete 删除订单
func (r *OrderRepository) Delete(id int64) error {
	query := `DELETE FROM orders WHERE id = ?`
	_, err := r.db.Exec(query, id)
	if err != nil {
		return fmt.Errorf("failed to delete order: %w", err)
	}
	return nil
}
